#Copyright (C) Nial Peters 2012
#
#This file is part of AvoScan.
#
#AvoScan is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#AvoScan is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with AvoScan.  If not, see <http://www.gnu.org/licenses/>.

from distutils.core import setup
import sys
import shutil
import os
import stat


required_modules = [("wx", "wxPython"),
                    ("Phidgets", "the Phidgets Python Interface"),
                    ("xlrd", "xlrd (the Python module for reading Excel spreadsheets)")
                   ]

#check that all the required modules are available
print "Checking for required Python modules..."
for mod, name in required_modules:
    try:
        print "importing " + mod + "..."
        __import__(mod)
    except ImportError:
        print "Failed to import \'" + mod + "\'. Please ensure that " + name + " is correctly installed, then re-run this installer."
        sys.exit(1)

#check that the Phidgets shared library is actually available
print "Checking for phidget21 shared library..."
import Phidgets.PhidgetLibrary
try:
    Phidgets.PhidgetLibrary.PhidgetLibrary.getDll()
except OSError:
    print "Failed to load phidget21 shared library. Please ensure that the phidgets21 library is installed correctly."
    sys.exit(1)
print "Checking version of pyserial..."
try:
    import serial
    if float(serial.VERSION < 2.6):
        print ("WARNING: python-serial (pyserial) module must be version 2.6 or " + 
               "later. You have version " + serial.VERSION + " This means that " + 
               "serial functionality will not be enabled.")
except ImportError:
    print ("WARNING: python-serial (pyserial) is not installed on your system. " + 
           "This means that serial functionality will not be enabled.")


if sys.platform == "linux2":
    apps_folder = '/usr/share/applications'
    icon_folder = '/usr/share/icons'
    desktop_folder = os.path.expandvars("$HOME/Desktop")
    
    avoscan_files_to_install = [(icon_folder, ['icons/avoscan.png']),
                        (apps_folder, ['misc/avoscan.desktop'])]
    avoscan_scripts_to_install = [os.path.normpath('src/AvoScan.py')]
      
elif sys.platform == "win32":
    avoscan_files_to_install = [("icons", [os.path.join('icons', 'avoscan.ico')])]
    avoscan_scripts_to_install = [os.path.join('src', 'AvoScan.py'), os.path.join('misc', 'avoscan_win32_postinstall.py')]
else:
    raise RunTimeError, "Unsupported platform"


setup(name='AvoScan',
      version='1.4',
      description='Program for operating AvoScanner scanning units.',
      author='Nial Peters',
      author_email='nonbiostudent@hotmail.com',
      package_dir={'':'src'},
      packages=['avoscan', 'avoscan.gui'],
      scripts=avoscan_scripts_to_install,
      data_files=avoscan_files_to_install 
      )


#post install
if sys.argv.count('install') != 0:
    if sys.platform == "linux2":
        try:
            you = os.getlogin()
        except OSError:
            you = os.path.expandvars("$LOGNAME")
        #TODO - this will return root!    
        if(you == "$LOGNAME"):
            raise RuntimeError, "Failed to determine your login name"
        #make sure the .desktop file on the desktop is executable
        for f in [desktop_folder + '/avoscan.desktop']:
            return_code = os.system("chmod a+x " + f)
            if return_code != 0:
                print "Error! Failed to change execute permissions on \'" + f + "\'"
        
        os.system("chown " + you + ":" + you + " " + desktop_folder + '/avoscan.desktop')

        #if running under linux, then install the udev rules file so that we can access the scanner 
        #without needing to be root      
        shutil.copy('misc/80_phidget.rules', '/etc/udev/rules.d/80_phidget.rules')
        os.chmod('/etc/udev/rules.d/80_phidget.rules', stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
    
